from django.shortcuts import render,redirect,HttpResponse
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from app01 import models
from app01 import forms
# Create your views here.
# def login(request):
#     if request.method == 'POST':
#         username = request.POST.get('username')
#         pwd = request.POST.get('password')
#         user = auth.authenticate(username =username,password = pwd)
#
#         if user:
#             auth.login(request, user)
#             return redirect('/index/')
#
#     return render(request,'login.html')
# @login_required
# def index(request):
#     print(request.user.username)
#     print('='*20)
#     return render(request,'index.html')
#
# def logout(request):
#     auth.logout(request)
#     return redirect('/login/')
#
# def register(request):
#     from django.contrib.auth.models import User
#     user_obj = User.objects.create_user(username='alex12',password='alex123')
#     # 校验密码是否正确
#     print(user_obj.check_password('alex111'))
#     # 重制密码
#     user_obj.set_password('alex444')
#     user_obj.save()
#     return HttpResponse('ok')
#
# from app01 import forms
#
# def register1(request):
#     if request.method=='POST':
#         form_obj=forms.RegForm(request.POST)
#         if form_obj.is_valid():
#             form_obj.cleaned_data.pop('re_password')
#             models.UserInfo.obj.create_user(**form_obj.cleaned_data)
#
#         else:
#             print(form_obj.errors)
#     form_obj = forms.RegForm()
#     return render(request,'register.html',{'form_obj':form_obj})

def register(request):
    if request.method =='POST':
        ret = {'status':0,'msg':''}
        form_obj = forms.RegForm(request.POST)
        if form_obj.is_valid():
            form_obj.cleaned_data.pop('re_password')
            avatar_img =request.FILES.get('avatar')
            models.UserInfo.objects.create_user(**form_obj.cleaned_data,avatar = avatar_img)
            ret['msg']='/index/'
            return JsonResponse(ret)
        else:
            ret['status']= 1
            ret['msg'] = form_obj.errors
            return JsonResponse(ret)
    form_obj = forms.RegForm()
    return render(request,'register1.html',{'form_obj':form_obj})

def logout(request):
    auth.logout(request)
    return redirect('/index/')

def login(reqeust):
    if reqeust.method =='POST':
        username = reqeust.POST.get('username')
        password = reqeust.POST.get('password')
        user = auth.authenticate(username=username,password=password)
        if user:
            auth.login(reqeust,user)
            return redirect('/index/')
        else:
            return render(reqeust,'login.html',{'msg':'用户或密码不正确'})
    return render(reqeust,'login.html')

def index(request):
    return render(request,'index.html')


def check_username_exist(request):
    ret = {'status':0,'msg':''}
    username = request.GET.get('username')
    is_exist = models.UserInfo.objects.filter(username = username)
    if is_exist:
        ret['status'] = 1
        ret['msg']='用户已被注册!'
    return JsonResponse(ret)

def index(request):
    # 查询所有的文章列表
    article_list = models.Article.objects.all()


    return render(request, "index.html", {"article_list": article_list})


def article_detail(request,username,pk):
    user = models.UserInfo.objects.filter(username=username).first()
    if not username:
        return HttpResponse('404')
    blog = user.blog
    article_obj = models.Article.objects.filter(pk=pk).first()

    comment_list = models.Comment.objects.filter(article_id = pk)
    return render(
        request,
        'article_detail.html',
        {
            'username':username,
            'article':article_obj,
            'blog':blog,
            'comment_list':comment_list
        }
    )
import json
from django.db.models import F
def up_down(request):
    print(request.POST)
    article_id = request.POST.get('article_id')
    is_up = json.loads(request.POST.get('is_up'))
    user = request.user
    response={'state':True}
    try:
        models.ArticleUpDown.objects.create(user=user,article_id=article_id,is_up=is_up)
        models.Article.objects.filter(pk=article_id).update(up_count=F('up_count')+1)
    except Exception as e:
        response['state']=False
        response['first_action']=models.ArticleUpDown.objects.filter(user=user,article_id=article_id).first().is_up
    return JsonResponse(response)

def comment(request):
    pid = request.POST.get('pid')
    article_id = request.POST.get('article_id')
    content = request.POST.get('content')
    user_pk=request.user.pk
    response={}
    if not pid:
        comment_obj = models.Comment.objects.create(article_id=article_id,content=content,user_id=user_pk)
    else:
        comment_obj = models.Comment.objects.create(article_id=article_id,user_id=user_pk,content=content,parent_comment_id=pid)
    response['create_time']=comment_obj.create_time.strftime('%Y-%m-%d')
    response['content']=comment_obj.content
    response['username']=comment_obj.user.username


    return JsonResponse(response)

def comment_tree(reqeust,article_id):
    ret=list(models.Comment.objects.filter(article_id=article_id).values('pk','content','parent_comment_id'))
    print(ret)
    return JsonResponse(ret,safe=False)

def home(request,username,*args):

    print(*args)
    user = models.UserInfo.objects.filter(username=username).first()
    if not user:
        return HttpResponse('404')
    blog = user.blog
    if not args:
        article_list = models.Article.objects.filter(user=user)
    else:
        if args[0]=='category':
            article_list = models.Article.objects.filter(user=user).filter(category__title=args[1])
        elif args[0]=='tag':
            article_list = models.Article.objects.filter(user=user).filter(tags__title=args[1])
        else:
            try:

                year,month = args[1].split('-')

                article_list = models.Article.objects.filter(user=user).filter(
                    create_time__year=year,create_time__month=month
                )

            except Exception as e:
                print(e)

                return HttpResponse('请求访问的日期归档格式不正确！！！')


    return render(request,'home.html',{
        'username':username,
        'blog':blog,
        'article_list':article_list,
    })


def add_article(request):
    if request.method=='POST':
        title = request.POST.get('title')
        article_content = request.POST.get('article_content')
        user = request.user
        from bs4 import BeautifulSoup
        bs = BeautifulSoup(article_content,'html.parser')
        desc = bs.text[0:150]+'..'
        for tag in bs.find_all():
            if tag.name in ['script','link']:
                tag.decompose()

        article_obj = models.Article.objects.create(user=user,title=title,desc=desc)
        models.ArticleDetail.objects.create(content=str(bs),article=article_obj)
        print(article_obj)
        return HttpResponse('添加成功')

    return render(request,'add_article.html')


from s10day75 import settings
import os
def upload(request):
    print(request.FILES)
    obj = request.FILES.get("upload_img")

    print("name",obj.name)

    path=os.path.join(settings.MEDIA_ROOT,"add_article_img",obj.name)

    with open(path,"wb") as f:
        for line in obj:
            f.write(line)


    res={
        "error":0,
        "url":"/media/add_article_img/"+obj.name,
    }


    return HttpResponse(json.dumps(res))